package dataStructure.a_record.singLinkedList;

/**
 * @author lhn
 * @date 2024-09-13 12:19
 */

public class SingleLinkedListDemo {
    public static void main(String[] args) {
        SingleLinkedList singleLinkedList = new SingleLinkedList();
        singleLinkedList.add(new Node(1, "a"));
        singleLinkedList.add(new Node(2, "b"));
        singleLinkedList.add(new Node(4, "e"));
        singleLinkedList.addByOrder(new Node(3, "c"));
        singleLinkedList.update(new Node(4, "d"));
        singleLinkedList.delete(3);

        singleLinkedList.list();
    }
}

class SingleLinkedList {
    Node head = null;
    public void addByOrder(Node node) {
        Node temp = head;
        if (head == null) {
            head = node;
            return;
        }
        while (temp.next != null ) {
            if (temp.next.no > node.no) {
                node.next = temp.next;
                temp.next = node;
                return;
            }
            temp = temp.next;
        }
        temp.next = node;
    }

    public void add(Node node) {
        Node temp = head;
        if (head == null) {
            head = node;
            return;
        }
        while (temp.next != null ) {
            temp = temp.next;
        }
        temp.next = node;
    }

    public void update(Node node) {
        Node temp = head;
        if (head == null) {
            System.out.println("链表为空");
            return;
        }
        while (temp != null) {
            if (temp.no == node.no) {
                temp.name = node.name;
                return;
            }
            temp = temp.next;
        }
    }

    public void delete(int no) {
        Node temp = head;
        if (head == null) {
            System.out.println("链表为空");
            return;
        }
        while (temp.next != null) {
            if (temp.next.no == no) {
                temp.next = temp.next.next;
                return;
            }
            temp = temp.next;
        }
    }


    public void list() {
        Node temp = head;
        if (head == null) {
            System.out.println("链表为空");
        }
        while (temp != null) {
            System.out.println(temp.no + " " + temp.name);
            temp = temp.next;
        }
    }
}

class Node {
    int no;
    String name;
    Node next;
    public Node() {
    }

    public Node(int no, String name) {
        this.no = no;
        this.name = name;
    }
}